package com.itheima.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.base.Area;
import com.itheima.bos.service.AreaService;
import com.itheima.bos.utils.PinYin4jUtils;
import com.itheima.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/area")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	@Autowired
	private AreaService areaService;
	
	private File file;
	private String fileContentType;
	private String fileFileName;
	
	public void setFile(File file) {
		this.file = file;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	/**
	 * 导入文件 添加区域数据到数据库中 
	 */
	@Action(value="area_importData",results={@Result(name="success",type="redirect",location="../pages/base/area.html")})
	public String area_importData(){
		List<Area> list = new ArrayList<Area>();
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
			HSSFSheet sheet = workbook.getSheetAt(0);
			for (Row row : sheet) {
				row.getCell(0).getStringCellValue();
				if(row.getRowNum() == 0){
					continue;
				}
				if(row != null && StringUtils.isNotBlank(row.getCell(0).getStringCellValue())){
					Area area = new Area();
					area.setId(row.getCell(0).getStringCellValue());
					area.setProvince(row.getCell(1).getStringCellValue());
					area.setCity(row.getCell(2).getStringCellValue());
					area.setDistrict(row.getCell(3).getStringCellValue());
					area.setPostcode(row.getCell(4).getStringCellValue());
						//排除省份,市,区的最后一个字
					String province = excludeLastOne(row.getCell(1).getStringCellValue());
					String city = excludeLastOne(row.getCell(2).getStringCellValue());
					String district = excludeLastOne(row.getCell(3).getStringCellValue());
					String[] short_code = PinYin4jUtils.getHeadByString(province + city + district);
					StringBuffer shortcode = new StringBuffer();
					for (String string : short_code) {
						shortcode.append(string);
					}
					
					area.setShortcode(shortcode.toString());
					area.setCitycode(PinYin4jUtils.hanziToPinyin(row.getCell(2).getStringCellValue(),""));
					list.add(area);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		areaService.importAllData(list);
		return SUCCESS;
	}
	
	public String excludeLastOne(String str){
		return str.substring(0, str.length() - 1);
	}
	
	@Action(value="area_pageQuery",results={@Result(name="success",type="json")})
	public String area_pageQuery(){
		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<Area> spec = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				Predicate predicate = null;
				if(StringUtils.isNotBlank(model.getProvince())){
					predicate = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
					list.add(predicate);
				}
				if(StringUtils.isNotBlank(model.getCity())){
					predicate  = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
					list.add(predicate);
				}
				if(StringUtils.isNotBlank(model.getDistrict())){
					predicate  = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
					list.add(predicate);
				}
				if(list.size() > 0 && list != null){
					Predicate ps[] = new Predicate[list.size()];
					query.where(list.toArray(ps));
				}
				query.orderBy(cb.desc(root.get("id").as(String.class)));
				return query.getRestriction();
			}
		};
		Page<Area> page = areaService.pageQuery(spec,pageable);
		pushPageDateToValueStack(page);
		return SUCCESS;
	}
}
